import time
import random
import hashlib
import sqlobject # this is python's simplest ORM

from connection import MysqlConnection

#
# This class is the ORM to database table message,
#		
class Message(sqlobject.SQLObject):
	class sqlmeta:
		createSQL = { 'mysql' : 
			[
				'ALTER TABLE message ENGINE InnoDB',
				'''ALTER TABLE message CHARACTER SET utf8'''
			]
		}
		
	#implicitly, sqlobject creates column 'id'
	
	# define the columns
	content = sqlobject.StringCol()
	direction = sqlobject.IntCol()
	status = sqlobject.IntCol(default=0)
	global_unique_id = sqlobject.StringCol(length=40)
	global_unique_index = sqlobject.DatabaseIndex('global_unique_id')
	
	DIRECTION_OUT = 1
	DIRECTION_IN = 2
	
	STATUS_NONE = 0
	STATUS_SUCCESS = 1
	STATUS_FAILED = 2
	
	# generate an absolutely unique id
	@classmethod
	def generate_global_id(cls, data):
		return hashlib.sha1(data + str(time.time()) + str(random.random())).hexdigest()
	
	# create message object
	# upon creation, data automatically stored in database (that is sqlobject feature)	
	@classmethod
	def create(cls, content, direction, global_unique_id=None):
		content = "%s" % content
		if not global_unique_id:
		  global_unique_id = Message.generate_global_id(content + str(direction))
		message = Message(content=content, direction=direction, global_unique_id=global_unique_id)
		return message
					